package com.sychip.fhc.app.wsn.screen

import android.graphics.Paint
import android.graphics.RectF
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateIntAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.BlurredEdgeTreatment
import androidx.compose.ui.draw.blur
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.fhc.base.EventObserver
import com.fhc.base.pxToDp
import com.fhc.view.dialog.FhcConfirmDialog
import com.fhc.view.utils.ToastyShow
import com.infinum.snacky.SnackyAnimationSpec
import com.infinum.snacky.SnackyDuration
import com.infinum.snacky.SnackyHost
import com.infinum.snacky.default.ShowDoNotReminderAgainSnackbar
import com.infinum.snacky.rememberSnackyHostState
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.common.NoUpdateBgColor
import com.sychip.fhc.app.wsn.common.NoUpdateFrColor
import com.sychip.fhc.app.wsn.common.util.rssiColor
import com.sychip.fhc.app.wsn.nav.PostToWsnDetail
import com.sychip.fhc.app.wsn.nav.RouterAvgPerDto
import com.sychip.fhc.app.wsn.nav.WsnNavigationItem.NavItem_Map
import com.sychip.fhc.app.wsn.nav.WsnTabNavigationActions
import com.sychip.fhc.app.wsn.screen.components.MovableDevice
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


val DEV_W = 60.dp
val DEV_H = 30.dp

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WsnMapScreen( navController: NavHostController = rememberNavController()){
    //mainTabViewModel: WsnMainTabViewModel? = null,
//    val appViewModel = MainApplication.instance().getAppViewModel()
//    val firstInit by viewModel.firstInitFlow.collectAsStateWithLifecycle()
//    if(firstInit){
////        viewModel.loadDevices()
//    }

//    navBackStackEntry 确保 ViewModel 与导航目的地生命周期绑定‌45。
//    同一目的地重复导航时，hiltViewModel() 会返回缓存的实例，避免重复初始化‌46。
    val navBackStackEntry = remember { navController.currentBackStackEntry }
    val viewModel: WsnMapViewModel = navBackStackEntry?.let { hiltViewModel(it) } ?: hiltViewModel()

    val toastState = remember { mutableStateOf<String?>(null) }

    // Show toast when message exists
    toastState.value?.let { message ->
        ToastyShow(msg = message){ }
        toastState.value = null
    }
    var sizeDev = Size(0f,0f)
    with(LocalDensity.current) {
        sizeDev = Size(DEV_W.toPx(), DEV_H.toPx())
    }
    var isMapVisible by remember { mutableStateOf(false) }

    EventObserver(onPause ={
        isMapVisible = false
    }, onResume ={
        isMapVisible = true
    })


    val showFilter by remember { mutableStateOf(true) }
    val filterState by viewModel.filterState.collectAsStateWithLifecycle()
    val isFilterExpanded = remember { mutableStateOf(false) }

    // 1. 状态管理

    val devFlow by viewModel.devFlow.collectAsStateWithLifecycle()

    val showAvgPer by viewModel.showAvgPer.collectAsStateWithLifecycle()


//    val animationSpec: AnimationSpec<Float> = if (devFlow.dataList.isEmpty()) keyframes {
//        durationMillis = 800
//        1f at 0 // 0-300ms保持1
//        1f at 500 // 500ms时仍为1
//        0f at 800 // 500-800ms过渡到0
//    } else {
//        tween(durationMillis = 300)
//    }

    var expanded by remember { mutableStateOf(false) }
    val showDeleteDialog = remember { mutableStateOf(false) }
    if (showDeleteDialog.value) {
        FhcConfirmDialog(appIcon = R.mipmap.ic_launcher,
            title= stringResource(R.string.wsn_q_delete_all_data),
            message = stringResource(R.string.wsn_q_delete_all_data_msg),
            onPositiveClick = {
                viewModel.clearAllData()
                showDeleteDialog.value = false
                expanded = !expanded
            },
            onNegativeClick = {
                showDeleteDialog.value = false
                expanded = !expanded
            },
            negativeButtonTxt = stringResource(R.string.text_cancel),
            positiveButtonTxt = stringResource(R.string.text_confirm)
        )
    }
    var topBarLayout: LayoutCoordinates? = null


    val snackbarHostState = rememberSnackyHostState()
    Scaffold(
        modifier = Modifier.fillMaxSize().combinedClickable(
            onClick = {
                expanded = false
            }
        ),
        snackbarHost = {
            SnackyHost(
                hostState = snackbarHostState,
                animationSpec = SnackyAnimationSpec(scaleFactor = 0.5f),
            )
        },
        topBar = {
            FhcTopAppBar(
                onTopAppBarPositioned = {layoutCoordinates ->
                    topBarLayout = layoutCoordinates
                },
                title = NavItem_Map.label,
                actions = {
//                    IconButton(onClick = {
//                        showFilter = !showFilter
//                        if(!showFilter){
//                            isFilterExpanded.value = false
//                        }
//                    }) {
//                        Box {
//                            Icon(
//                                if(showFilter) Icons.Filled.FilterAlt else Icons.Filled.FilterAltOff,
//                                contentDescription = null,
//                                tint = colorScheme.onPrimary
//                            )
//                        }
//                    }
                }

            )
        },
        floatingActionButton = {
            if(!devFlow.dataList.isEmpty()){

                Column(
                    horizontalAlignment = Alignment.End,
                    modifier = Modifier

                ) {
                    AnimatedVisibility(
                        visible = expanded,
                        enter = fadeIn() + slideInVertically { it },
                        exit = fadeOut() + slideOutVertically { it }
                    ) {
                        Column(
                            verticalArrangement = Arrangement.spacedBy(8.dp),
                            modifier = Modifier.padding(end = 0.dp, bottom = 16.dp)
                        ) {
                            FloatingActionButton(
                                onClick = {
                                    viewModel.toggleShowAvgPer()
                                },
                                containerColor = Color.White,

                                ) {
                                Icon(
                                    painterResource(id = R.drawable.ic_percent),
                                    modifier = Modifier.background(if (showAvgPer) colorScheme.primary else Color.White),
                                    tint = if (!showAvgPer) colorScheme.primary else Color.White,
                                    contentDescription = null
                                )
                            }

                            FloatingActionButton(
                                onClick = {

                                    viewModel.highlightDevice(null)
                                    isFilterExpanded.value = false
//                                Timber.i("------------------showLineFromNow 000000000-------------------")
                                    viewModel.showLineFromNow()
                                },
                                containerColor = colorScheme.errorContainer,

                                ) {
                                Icon(Icons.Default.Refresh, null)
                            }

                            FloatingActionButton(
                                onClick = {
                                    viewModel.highlightDevice(null)
                                    isFilterExpanded.value = false
                                    if(!showDeleteDialog.value){
                                        showDeleteDialog.value = true
                                    }
                                },
                                containerColor = colorScheme.errorContainer,
                            ) {
                                Icon(Icons.Default.Delete, "删除")
                            }
                        }
                    }

                    FloatingActionButton(
                        onClick = {
                            expanded = !expanded
                            viewModel.highlightDevice(null)
                        },
                        modifier = Modifier.size(56.dp),
                        containerColor = colorScheme.primary,
                        contentColor = colorScheme.onPrimary,
                        shape = CircleShape
                    ) {
                        AnimatedContent(
                            targetState = expanded,
                            label = "icon_animation"
                        ) { isExpanded ->
                            Icon(
                                if (isExpanded) Icons.Default.Close else Icons.Default.Menu,
                                "主菜单"
                            )
                        }
                    }
                }
            }
        }
    ) { innerPadding ->
        var isOpeningDetail = false
        val devFlow by viewModel.devFlow.collectAsStateWithLifecycle()
        val blurRadius by animateIntAsState(
            targetValue = if (isFilterExpanded.value) 6 else 0,
            animationSpec = tween(durationMillis = 300),
            label = "blur_animation"
        )
        var parentSize by remember { mutableStateOf(IntSize.Zero) }

        val devsFilter by viewModel.devFilterFlow.collectAsStateWithLifecycle()
        Box(modifier = Modifier
            .padding(top = innerPadding.calculateTopPadding()).padding(top = if(!devFlow.dataList.isEmpty() && showFilter) FilterHeight else 0.dp)
            .fillMaxSize().onGloballyPositioned { layoutCoordinates ->
                parentSize = layoutCoordinates.size
//                if(prevOrientation != currOrientation) Timber.i("rememberOrientationWithHistory        prevOrientation: %s   currOrientation:%s" ,  prevOrientation,currOrientation )
                viewModel.setMapDevSize(parentSize.width, parentSize.height, sizeDev.width.toInt(), sizeDev.height.toInt())
            }) {
            if(devFlow.dataList.isEmpty()){
                RssiEmptyView()
            }else {
                Box(modifier = Modifier.fillMaxSize()
                    .clickable(onClick = {
                        viewModel.highlightDevice(null)
                    }).then(if (isFilterExpanded.value) Modifier.blur(blurRadius.dp, BlurredEdgeTreatment.Unbounded) else Modifier)) {
                    val navActions: WsnTabNavigationActions = remember(navController) { WsnTabNavigationActions(navController) }

                    val lineFilterFlow by viewModel.lineFilterFlow.collectAsStateWithLifecycle()
                    val showAvgPer by viewModel.showAvgPer.collectAsStateWithLifecycle()
                    val avgPerDataFlow by viewModel.avgPerDataFlow.collectAsStateWithLifecycle()
                    MapRssiLineContent(isMapVisible, lineFilterFlow,showAvgPer,avgPerDataFlow,
                        onRssiLineClick = { line ->
                            if (isOpeningDetail) return@MapRssiLineContent
                            isOpeningDetail = true
                            val param = PostToWsnDetail(line.wsnDev.fromDevId, line.wsnDev.toDevId, 0L, 0L)
                            navActions.navigateToWsnListDetail(param)
                            MainApplication.instance().showBottomNavbar(false)
                            CoroutineScope(Dispatchers.Main).launch {
                                delay(500)
                                isOpeningDetail = false
                            }
                        },
                        onTapContainer = {
                            viewModel.highlightDevice(null)
                            expanded = false
                        }
                    )
                    if(isMapVisible && devsFilter.isNotEmpty()){
                        devsFilter.forEach { device ->
                            key(device.devId) {
                                MovableDevice(
                                    device = device,
                                    selfSize = DpSize(DEV_W, DEV_H),
                                    selfOffset = Offset(device.offsetX, device.offsetY),
                                    containerSize = parentSize,
                                    onDragMove =  { device, offsetX, offsetY ->
                                        viewModel.updateDeviceXY(device, offsetX, offsetY)
                                        expanded = false
                                        //                    //得放在外面调用，不能在updateDeviceXY内updateRssiXY，会导致刷新有点乱
                                        //                    viewModel.updateRssiXY(device)
                                    },
                                    onDragEnd = { device, offsetX, offsetY ->
                                        viewModel.updateDeviceXY(device, offsetX, offsetY)
                                        //                    //得放在外面调用，不能在updateDeviceXY内updateRssiXY，会导致刷新有点乱
                                        //                    viewModel.updateRssiXY(device)
                                    },
                                    onGloballyPositioned = { _, _ -> },
                                    onClick = {
                                        viewModel.highlightDevice(device)
                                    }
                                )



                                //            MovableTextBox(
                                //                moveObject = device,
                                //                bgColor = device.bgColor,
                                //                txtColor = device.txtColor,
                                //                boxName = device.devId,
                                //                selfSize = DpSize(DEV_W, DEV_H),
                                //                selfOffset = Offset(device.offsetX, device.offsetY),
                                //                containerSize = parentSize,
                                //                onDragMove = onDeviceMove,
                                //                onDragEnd = onDragEnd,
                                //                onGloballyPositioned = { dev, offset -> },
                                //                dataUpdated = device.rssiUpdated,
                                //                onClick = {
                                //                    onDeviceClick(device)
                                //                },
                                //                unHighlight = device.unHighlight
                                //            )

                            }
                        }
                    }

                }

            }

//            if(!IS_DEBUG){
//                FilterRow(showFilterTop = showFilterTop, searchQuery = searchQuery, onDismiss = {
//                    viewModel.closeFilterTop()
//                })
//            }

//            if(showFilterTop){
//                Row(
//                    modifier = Modifier.fillMaxWidth().background(Color.Black.copy(alpha = 0.8f)),
//                    horizontalArrangement = Arrangement.SpaceBetween,
//                    verticalAlignment = Alignment.CenterVertically
//                ) {
//                    Text(
//                        text = "Filter: $searchQuery",
//                        modifier = Modifier.weight(1f),
//                        color = Color.White,
//                        textAlign = TextAlign.Center
//                    )
//                    IconButton(
//                        onClick = { showFilterTop = false }
//                    ) {
//                        Icon(
//                            imageVector = Icons.Default.Hi,
//                            contentDescription = "关闭", tint = Color.White
//                        )
//                    }
//                }
//            }

//            if(!IS_DEBUG && showFilter){
//                FilterContent(query = searchQuery,
//                    regex = Regex("[^a-zA-Z0-9 ]"),
//                    onQueryChange={searchQuery->
//                        viewModel.updateFilter(searchQuery)
//                    }, onBackgroundClick = {
//                        showFilter = false
//                    })
//            }
        }
    }
    viewModel.firstInitFinished()

    val remindDeviceBeyondMap by viewModel.remindDeviceBeyondMapFlow.collectAsStateWithLifecycle()
    if(remindDeviceBeyondMap) {
        ShowDoNotReminderAgainSnackbar(
            showState = remember { mutableStateOf(true) },
            message = stringResource(R.string.wsn_w_app_size_dev_map),
            snackbarHostState = snackbarHostState,
            duration = SnackyDuration.Indefinite,
            okAction = { dnd ->
                if (dnd) {
                    viewModel.doNotRemind()
                }
                viewModel.closeRemind()
            },
            onDismiss = {
                viewModel.closeRemind()
            }
        )
    }

    var filterTopPadding by remember { mutableFloatStateOf(0f) }

    LaunchedEffect(topBarLayout) {
        if (topBarLayout != null) {
            filterTopPadding = topBarLayout.positionInWindow().y+ topBarLayout.size.height
        }
    }


//    val statusBarHeight = with(LocalContext.current) {
//        val windowMetrics = getSystemService(WindowManager::class.java).currentWindowMetrics
//        val insets = windowMetrics.windowInsets
//        val systemBarsInsets = insets.getInsets(WindowInsets.Type.systemBars())
//        val statusBarHeight = systemBarsInsets.top
//        val navBarHeight = systemBarsInsets.bottom
//        statusBarHeight + navBarHeight - 10
//    }


    if(!devFlow.dataList.isEmpty()){
        val lineFilterFlow: MutableList<MapDeviceLineDto> by viewModel.lineFilterFlow.collectAsStateWithLifecycle()
        val lineFlow: MutableList<MapDeviceLineDto> by viewModel.lineFlow.collectAsStateWithLifecycle()

        var filterResult by remember { mutableStateOf("") }
        LaunchedEffect(key1 =lineFlow.size,key2= lineFilterFlow.size, key3 = filterState) {
            filterResult = if(filterState.isFilterDevIds || filterState.isFilterRssi) " ${lineFilterFlow.size} / ${lineFlow.size} "
            else " ${lineFlow.size} "
        }
        if(showFilter) {
            MultipleFilterRow(
                modifier = Modifier.padding(top = filterTopPadding.pxToDp()),
                isExpanded = isFilterExpanded,
                filter = filterState,
                filterResult = filterResult,
                onFilterCollapseStart = {
                    expanded = false

                    viewModel.highlightDevice(null)
//                showFilter = !collapse
                },
                onFilterCollapseStop = {
                    expanded = false

                    viewModel.highlightDevice(null)
//                showFilter = !collapse
                },
                onFilterChanged = { newFilter ->
                    viewModel.updateFilterDto(newFilter)
                })
        }
    }
}


data class MapRouterLine   (
    val lineDto: MapDeviceLineDto,
    val rssi: String,
    var isVisible: Boolean,
)

@Composable
private fun MapRssiLineContent(isMapVisible: Boolean = true,
                               lineFilterFlow: MutableList<MapDeviceLineDto>,
                               showAvgPer: Boolean,
                               avgPerDataFlow: MutableList<RouterAvgPerDto>,
                               onRssiLineClick: (MapDeviceLineDto) -> Unit,
                               onTapContainer: () -> Unit = {}){

    val animatedLines =lineFilterFlow.map { lineDto ->
       val objLine = MapRouterLine(lineDto, lineDto.wsnDev.rssi.toString(), true)

       val aniDelay= 200L
       if(lineDto.isLineShow){
            if(!lineDto.isNoUpdate60s){
                if(lineDto.isUpdatedIn1s && isMapVisible ){
                    var visibleAnim by remember { mutableStateOf(true) }
                    LaunchedEffect(lineDto.wsnDev.dateTime) {
                        delay(aniDelay)
                        visibleAnim = false
                        delay(aniDelay)
                        visibleAnim = true
                        delay(aniDelay)
                        visibleAnim = false
                        delay(aniDelay)
                        visibleAnim = true
                    }
                    objLine.isVisible = visibleAnim
                }else{
                    objLine.isVisible = true
                }
            }
        }
        objLine
    }
    var lastClickTime = 0L
    if(!isMapVisible){
        Canvas(modifier = Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                detectTapGestures {
                    onTapContainer()
                }
            }) {
        }
    }else{
        Canvas(modifier = Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                detectTapGestures { offset ->
                    onTapContainer()
                    // offset包含x/y坐标
                    val currentTime = System.currentTimeMillis()
                    if (currentTime - lastClickTime > 300) { // 300ms间隔
                        lastClickTime = currentTime
                        lineFilterFlow.forEach { line ->
                            if (line.rect.contains(offset.x, offset.y)) {
                                onRssiLineClick(line)
                                return@forEach
                            }
                        }
                    }
                }
            }) {
            //以下分开两部分循环的原因是，如果showAvgPer = true，执行删除全部数据后，接受到新的rssi时，line会画在avg per上方
            animatedLines.forEach {route ->
                if(route.lineDto.isLineShow && route.isVisible){
                    val lineColor = if(route.lineDto.isNoUpdate60s){
                        NoUpdateBgColor.copy(alpha = 0.5f)
                    } else{
                        route.lineDto.wsnDev.rssi.rssiColor().copy(alpha = if(route.lineDto.isUnFocused) 0.3f else 1f)
                    }
                    drawLine(
                        start = route.lineDto.fromPoint,
                        end = route.lineDto.toPoint,
                        color =  lineColor,
                        strokeWidth = (if(route.lineDto.isUpdatedIn1s) 6 else 2).dp.toPx(),
                        pathEffect = PathEffect.dashPathEffect(floatArrayOf((if(route.lineDto.isUpdatedIn1s) 40f else 12f),4f), 0f)
                    )
                }

            }
            animatedLines.forEach {route ->
                if(route.lineDto.isLineShow && route.isVisible){
                    var rssiTxt:String
                    if(showAvgPer){
//                        repeater1->repeater2  repeater2->repeater1可能同时存在，使用最小的PER，相当于把最小的per显示在最前
                        val avgPer1 = avgPerDataFlow.find { it.fromDevId == route.lineDto.wsnDev.fromDevId && it.toDevId == route.lineDto.wsnDev.toDevId }
                        val avgPer2 = avgPerDataFlow.find { it.toDevId == route.lineDto.wsnDev.fromDevId && it.fromDevId == route.lineDto.wsnDev.toDevId }


                        rssiTxt =  try {
                            if(avgPer2  != null  &&  avgPer1  != null && avgPer2.per != "--" && avgPer1.per != "--" && avgPer2.per.toInt() > avgPer1.per.toInt()){
                                "${avgPer2.avg} / ${avgPer2.per}%"
                            }else{
                                if(avgPer1 != null) "${avgPer1.avg} / ${avgPer1.per}%"
                                else "-- / --%"
                            }
                        }catch (_:Exception){
                            if(avgPer1 != null) "${avgPer1.avg} / ${avgPer1.per}%"
                            else "-- / --%"
                        }
                    }else{
                        rssiTxt = route.lineDto.wsnDev.rssi.toString()
                    }

                    // 文字测量与居中绘制
                    val text = rssiTxt
                    val txtColor = if(route.lineDto.isNoUpdate60s){
                        NoUpdateFrColor.copy(alpha = 0.8f).toArgb()
                    }else{
                        if(route.lineDto.isUnFocused) Color.White.copy(alpha=0.2f).toArgb()
                        else Color.Black.copy(alpha=0.8f).toArgb()
                    }  // 背景色 // 0xB2表示70%透明度(0.7*255≈178→0xB2)
                    val textPaint = Paint().apply {
                        textSize = 14.sp.toPx() // 增大字体
                        color =  txtColor
                        textAlign = Paint.Align.CENTER
                        isAntiAlias = true // 抗锯齿
                        isFakeBoldText = true // 粗体
                    }

                    // 计算文字基线位置（垂直居中）
                    val fontMetrics = textPaint.fontMetrics
                    val textHeight = fontMetrics.descent - fontMetrics.ascent
                    val textWidth = textPaint.measureText(text)
                    val baseline = route.lineDto.middlePoint.y + (textHeight / 2 - fontMetrics.descent)

                    // 添加背景绘制
                    val bgLRPadding = 8.dp.toPx() // 增加背景间距
                    val bgTBPadding = 3.dp.toPx() // 增加背景间距

//                // 绘制阴影效果
//                val shadowPaint = Paint().apply {
//                    color = 0x66FFFFFF.toInt() // 半透明黑色阴影
//                    style = Paint.Style.FILL
//                    isAntiAlias = true
//                }

//                // 绘制边框
//                val strokePaint = Paint().apply {
//                    color = android.graphics.Color.BLACK // 黑色边框
//                    style = Paint.Style.STROKE
//                    strokeWidth = 2f
//                    isAntiAlias = true
//                }
//
                    val bgColor = if(route.lineDto.isNoUpdate60s){
                        NoUpdateBgColor.copy(alpha = 0.8f).toArgb()
                    }else{
                        if(route.lineDto.isUnFocused) Color.Black.copy(alpha=0.2f).toArgb()
                        else Color.White.copy(alpha=0.8f).toArgb()
                    }  // 背景色 // 0xB2表示70%透明度(0.7*255≈178→0xB2)
                    // 主背景绘制
                    val bgPaint = Paint().apply {
                        color = bgColor
                        style = Paint.Style.FILL
                        isAntiAlias = true
                    }

                    // 计算背景矩形位置
                    val bgLeft = route.lineDto.middlePoint.x - textWidth/2 - bgLRPadding
                    val bgTop = baseline + fontMetrics.ascent - bgTBPadding
                    val bgRight = route.lineDto.middlePoint.x + textWidth/2 + bgLRPadding
                    val bgBottom = baseline + fontMetrics.descent + bgTBPadding
                    route.lineDto.rect = RectF(bgLeft, bgTop, bgRight, bgBottom)

//                // 绘制阴影（偏移一点位置）
//                drawContext.canvas.nativeCanvas.drawRoundRect(
//                    bgLeft + 2f, bgTop + 2f, bgRight + 2f, bgBottom + 2f,
//                    10f, 10f,
//                    shadowPaint
//                )
//
                    // 绘制主背景
                    drawContext.canvas.nativeCanvas.drawRoundRect(
                        bgLeft, bgTop, bgRight, bgBottom, 10f, 10f,
                        bgPaint
                    )

//                // 绘制边框
//                drawContext.canvas.nativeCanvas.drawRoundRect(
//                    bgLeft, bgTop, bgRight, bgBottom, 10f, 10f,
//                    strokePaint
//                )

                    // 绘制文字
                    drawContext.canvas.nativeCanvas.drawText(
                        text,
                        route.lineDto.middlePoint.x,
                        baseline,
                        textPaint
                    )

                }

            }
        }

    }

}

